#!/usr/bin/python

#demo

import os
import sys
import inspect
import thread
import time
import ctypes
import logging
import syslog

def get_thread_id():
	SYS_gettid = 186
	libc = ctypes.cdll.LoadLibrary('libc.so.6')
	tid = libc.syscall(SYS_gettid)
	return tid

def myfun(fname,*arg):
        global x
        a_lock.acquire()
        print fname,"=",thread.get_ident()
        for i in range(3):
                x=x+1
                print "\t",thread.get_ident(),"\t=\t",x
        a_lock.release()
        time.sleep(100)
        return

def test():
	print "come in=",__name__
	print "curdir=" , os.path.abspath(os.curdir)

	list_threads=[]
	for i in range(1,5):
                thread.start_new_thread(myfun,("Thread No:"+str(i),))
        time.sleep(1)
        f01()
	return


def f01():
        print "come in=",sys._getframe(0).f_code.co_name
	print "SYS_gettid=",get_thread_id() 
	return

def t01(value=1):
        print "arg=",value ,"\tcome in=",sys._getframe(0).f_code.co_name
	#print inspect.stack()
	stack_print(inspect.stack())
	return

def t02(value=2):
        print "arg=",value ,"\tcome in=",sys._getframe(0).f_code.co_name
	t01()
	return

def t03(value=3):
        print "arg=",value ,"\tcome in=",sys._getframe(0).f_code.co_name
	t02()
	return

def t04(value=4):
        print "arg=",value ,"\tcome in=",sys._getframe(0).f_code.co_name
	t03()
	return

def stack_print(stack_list):
	print "----------stack display------------"
	for tmp in stack_list:
		print tmp
	print "----------stack end------------"
	return

def test_logger():
        logger=logging.getLogger("python_test_logger")
        logger.setLevel(logging.DEBUG)

        target = logging.StreamHandler()
        target.setLevel(logging.DEBUG)
        logger.addHandler(target)

        for i in range(10):
                logger.info("test info:"+str(i))

        return

def test_syslog():
        syslog.openlog("mydemo_python")
        for i in range(5):
                syslog.syslog("test syslog info:"+str(i))
        return

if __name__ == '__main__':

	print "hello"
	t04()  #test callstack

	x=0   #global test value.
        a_lock = thread.allocate_lock()

	test()  #test threads

        print "------- logger -------"
        test_logger()
        test_syslog()


        time.sleep(500)


	
	
